import { createRouter, createWebHashHistory,createWebHistory } from "vue-router"
import { getToken } from '@/libs/token.js'
import {routes} from './routes.js'
import { userStore } from '@/pinia/store.js'
import { MODE } from "@/libs/constants"
import {authentication} from '@/api/登录.js'
function routeAdd(route){
    if(route){
        const routesStr = JSON.parse(route)
        routesStr.forEach(_ => {
            /* _.component = () => import(`@/layout/${_.name}/${_.name}.vue`)*/
            _.component = () => import(`@/layout/${_.name}/${_.name}.vue`)
            router.addRoute('main',_)
        })
    }
}
const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach(async (to,from,next) => {
    let token = getToken()
    let res
    if(token) {
        res = await authentication()
        if(res.code !== 0 && to.name === 'error'){
            return next()
        } else if (res.code !== 0 && to.name !== 'error'){
            return next({name:'error'})
        } else if(res.code === 0 && to.name === 'error'){
            return next({name:'Benefit'})
        }
    }
    if(MODE === 'development'){
        if((!token && to.name === 'login')){
            return next()
        } else if(!token && to.name !== 'login'){
            return next({
                name:'login'
            })
        } else if((token && to.name === 'login' && res.code === 0)) {
            return next({
                name:'Benefit'
            })
        }
    } else {
        if(!token && to.name === 'error'){
            return next()
        } else if(!token && to.name !== 'error'){
            return next({
                name:'error'
            })
        }
    }
    return next()
})
export default router